package com.springapp.tomcat;

import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ErrorReportValve;

import java.io.*;

/**
 * Created by nkrivko on 25.12.2014.
 */
public class    FrontendErrorPage extends ErrorReportValve {

    @Override
    protected void report(org.apache.catalina.connector.Request request, Response response, Throwable throwable) {
        // Do nothing on non-HTTP responses
        // Do nothing on a 1xx, 2xx and 3xx status
        // Do nothing if anything has been written already
        if ((response.getStatus() > 400) && (response.getContentWritten() == 0)) {
            response.setCharacterEncoding("utf-8");
            try (InputStream stream = this.getClass().getResourceAsStream("/error.html");
                 BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
                Writer responseReporter = response.getReporter();
                String line;
                while ((line = reader.readLine()) != null) {
                    responseReporter.write(line);
                }
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }
    }

}
